//
//  ProductDetailViewController.m
//  ExhibitionHall
//
//  Created by 王洋 on 2019/5/29.
//  Copyright © 2019 王洋. All rights reserved.
//

#if TARGET_IPHONE_SIMULATOR//模拟器
#elif TARGET_OS_IPHONE//真机
#import <Ar100Sdk/Ar100Sdk.h>
#endif

//视频播放
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>

#import "ProductInfoCell.h"
#import "ProductSKUCell.h"
#import <WebKit/WebKit.h>

#import "ProductInfoModel.h"
#import "ProductSKUModel.h"

#import "ProductDetailBannerCell.h"
#import "ProductDetailWebFooterView.h"
#import "ProductDetailViewController.h"
#import "TTVideoPlayViewController.h"
#import "normalTableViewCell.h"


@interface ProductDetailViewController ()<
UITableViewDelegate,
UITableViewDataSource,
UIScrollViewDelegate,
WKNavigationDelegate
> {
    CGFloat webContentHeight;
}

@property (nonatomic, strong) WKWebView *VRView;
@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) NSMutableArray *bannerArray;
@property (nonatomic, strong) ProductInfoModel *productInfoModel;

@property (nonatomic, strong) NSMutableArray *totalSKUInfos;
@property (nonatomic, strong) NSMutableArray <ProductSKUModel *>* totalSKUArray;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, copy)   NSString *price;


@property (nonatomic, strong) ProductDetailWebFooterView *webFooterView;
@property (nonatomic, strong) UIView *maskView;
@property (nonatomic, strong) UIImageView *sunCodeImageView;
@property (nonatomic, assign) CGFloat contextCellHeight;//图文详情web高度


@property(nonatomic, strong) UIButton *panoramaBtn;  //全景
@property(nonatomic, strong) UIButton *videoBtn;  //视频
@property(nonatomic, strong) UIButton *arShopingBtn;  //AR购物
@property(nonatomic, strong) UIButton *detailBtn;  //详情


@property (nonatomic, strong) NSMutableArray <NSMutableDictionary *>*ARModelArray;
#if TARGET_IPHONE_SIMULATOR//模拟器
#elif TARGET_OS_IPHONE//真机
@property (strong, nonatomic) Ar100Maganer *ar100Maganer;

#endif

@end

@implementation ProductDetailViewController

- (void)dealloc {
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.ARModelArray = @[].mutableCopy;
    self.productInfoModel = [[ProductInfoModel alloc] init];
    self.totalSKUInfos = @[].mutableCopy;
    self.totalSKUArray = @[].mutableCopy;
    self.selectIndex = 0;
    [self initView];
    
    
    [self requestData];

    self.view.backgroundColor = [UIColor lightGrayColor];
    [self.webFooterView reloadHtmlWithStr:[NSString stringWithFormat:@"%@%@",TT_Global_H5_Domain,self.productID]];
    _contextCellHeight = 44.0;


    [self.VRView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://beyond.3dnest.cn/play/index.html?m=zq_jlthm_71&o=jlt023"]]];

    self.tableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;

}

- (void)requestData {
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_GOODDETAIL_API];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:self.productID forKey:@"id"];
    WEAKSELF
    [TTHttpManager getRequestWithUrl:url TimeOut:10.0 GetData:param FinishBlock:^(id  _Nonnull data) {
        
        BOOL fail = [[data valueForKey:@"code"] boolValue];
        NSDictionary *resultDic = [data valueForKey:@"data"];
        if (!fail) {
            
            //banner
            NSArray *pics = [resultDic valueForKey:@"pics"];
            weakSelf.bannerArray = pics.mutableCopy;
            
            //goodinfo
            weakSelf.productInfoModel.name =[resultDic valueForKey:@"name"];
            weakSelf.productInfoModel.price = [resultDic valueForKey:@"price"];
            weakSelf.price = [resultDic valueForKey:@"price"];
            
            weakSelf.ARModelArray = [resultDic valueForKey:@"modelParams"];
            
            //获取sku
            NSArray *skuArr = [resultDic valueForKey:@"types"];
            [weakSelf fillArrayWithArray:skuArr];
            
            //获取太阳码
            [weakSelf.sunCodeImageView sd_setImageWithURL:[NSURL URLWithString:[resultDic valueForKey:@"sunCode"]]];
            [weakSelf.tableview reloadData];
            
        } else {
            
            [WHToast showErrorWithMessage:[resultDic valueForKey:@"message"] duration:TT_GLOBAL_DURATION_TIME finishHandler:^{
                
            }];
        }

    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

- (void)fillArrayWithArray:(NSArray *)arr{
    self.totalSKUArray = @[].mutableCopy;
    for (int i = 0; i< arr.count; i++) {
        ProductSKUModel *firstModel = [[ProductSKUModel alloc] init];
        firstModel.name = [arr[i] valueForKey:@"name"];
        firstModel.isSelect = NO;
        NSArray *childs = [arr[i] valueForKey:@"content"];
        firstModel.skuArray = @[].mutableCopy;
        for (int j = 0; j < childs.count; j++) {
            ProductSKUModel *childModel = [[ProductSKUModel alloc] init];
            childModel.name = [childs[j] valueForKey:@"name"];
            childModel.price = [childs[j] valueForKey:@"price"];
            childModel.isSelect = NO;
            [firstModel.skuArray addObject:childModel];
        }
        [self.totalSKUArray addObject:firstModel];
    }
    
}

- (void)initView {
    
    [self.view addSubview:self.VRView];
    
    [self.VRView addSubview:self.panoramaBtn];
    [self.VRView addSubview:self.videoBtn];
    [self.VRView addSubview:self.arShopingBtn];
    [self.VRView addSubview:self.detailBtn];
    
    [self.view addSubview:self.maskView];
    [self.maskView addSubview:self.tableview];
    [self.maskView addSubview:self.sunCodeImageView];
    
    self.maskView.hidden = YES;
    
    [self.VRView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo([TT_SizeHelper getGlobalStatusBarHeight]);
        make.left.right.bottom.mas_equalTo(0);
    }];
    
    
    [self.panoramaBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(135);
        make.centerY.mas_equalTo(-100);
        make.right.mas_equalTo(25);
    }];
    
    [self.videoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(self.panoramaBtn);
        make.top.mas_equalTo(self.panoramaBtn.mas_bottom).offset(20);
        make.right.mas_equalTo(30);
    }];
    
    [self.arShopingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(self.panoramaBtn);
        make.top.mas_equalTo(self.videoBtn.mas_bottom).offset(20);
        make.right.mas_equalTo(30);
    }];
    
    [self.detailBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(self.panoramaBtn);
        make.top.mas_equalTo(self.arShopingBtn.mas_bottom).offset(20);
        make.right.mas_equalTo(25);
    }];
    
    [self.maskView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo([TT_SizeHelper getGlobalStatusBarHeight]);
    }];
    
    [self.sunCodeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-10);
        make.bottom.mas_equalTo(0);
        make.width.height.mas_equalTo(0.25 * TTScreenWidth- 20);
    }];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.width.mas_equalTo(TTScreenWidth * 0.5);
        make.centerX.mas_equalTo(0);
    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            ProductDetailBannerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bannerCellID" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

            [cell configBannerCellWithModel:self.bannerArray ImgClickedBlock:^(NSInteger index) {
                
            }];
            return cell;
            
        }
    } else if (indexPath.section == 1){
        
            ProductInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ProductInfoCellID" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

            [cell fillCellWithModel:self.productInfoModel];
            return cell;

    } else if (indexPath.section == 2){
        WEAKSELF
        ProductSKUCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ProductSKUCellID" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        if (indexPath.row ==0) {
            [cell fillCellWithTitle:@"一级品类" Array:self.totalSKUArray];
            cell.skuClickBlock = ^(NSInteger index) {
              
                //去掉其他选中状态    设立当前选中状态
                weakSelf.selectIndex = index;  //供二级sku取值使用
                for (int i=0; i<self.totalSKUArray.count; i++) {
                    self.totalSKUArray[i].isSelect = NO;
                }
                self.totalSKUArray[index].isSelect = YES;
                
                
                //如果只有一级sku，就取初始价格
                if (self.totalSKUArray.count > index &&self.totalSKUArray[index].skuArray.count == 0) {
                    //把原来的价格设置到价格区域
                    weakSelf.productInfoModel.price = weakSelf.price;
                }
                
                [self.tableview reloadData];
            };
            
        } else {
            
            [cell fillCellWithTitle:@"二级品类" Array:self.totalSKUArray[weakSelf.selectIndex].skuArray];
            
            cell.skuClickBlock = ^(NSInteger index) {
                
                //刷新当前选中状态
                
                NSArray<ProductSKUModel *>*arr = weakSelf.totalSKUArray[weakSelf.selectIndex].skuArray;
                for (int i=0; i<arr.count; i++) {
                        arr[i].isSelect = NO;
                }
                arr[index].isSelect = YES;
                weakSelf.totalSKUArray[weakSelf.selectIndex].skuArray = arr.mutableCopy;

                
                //改变infocell的价格
                if (weakSelf.totalSKUArray.count > weakSelf.selectIndex && weakSelf.totalSKUArray[weakSelf.selectIndex].skuArray.count > index) {
                    
                    weakSelf.productInfoModel.price = weakSelf.totalSKUArray[weakSelf.selectIndex].skuArray[index].price;
                }
                
                [weakSelf.tableview reloadData];
            };
        }
        
        return cell;
        
    } else {
        
        normalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"normalTableViewCellID" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor whiteColor];
        return cell;
        
    }
    
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat height = 100.0f;
    switch (indexPath.section) {
        case 0:{
            height = TTScreenWidth * 0.5 ;
        }break;
        case 1:{
            height = 100.0f;
        }break;
        case 2:{
            height = 100.0f;
        }break;
        case 3:{
            height = 10.0f;
        }break;
        default: break;
    }
    return height;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSInteger num = 1;
    switch (section) {
        case 0:{//banner
            num = 1;
            
        }break;
            
        case 1:{//h商品信息
            num = 1;
        }break;
            
        case 2:{//SKU信息
            if (self.totalSKUArray.count > self.selectIndex) {
                if (self.totalSKUArray[self.selectIndex].skuArray.count >0) {
                    num = 2;
                } else {
                    num = 1;
                }
            }
        }break;
        case 3:{//h商品信息
            num = 1;
        }break;
        default: break;
    }
    
    return num;

}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 3) {
        return self.webFooterView;

    } else {
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor redColor];
        return view;

    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (section == 3) {
        return _contextCellHeight;
    } else {
        return 0;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor blackColor];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}


- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    
    if (webView.tag != 100) {
                
            __weak typeof(self)weakSelf = self;
            [webView evaluateJavaScript:@"document.body.offsetHeight;" completionHandler:^(id _Nullable obj, NSError * _Nullable error) {

                weakSelf.contextCellHeight = [obj floatValue];
                weakSelf.contextCellHeight = 1700.0f;

                [webView sizeThatFits:CGSizeMake(weakSelf.view.bounds.size.width, weakSelf.contextCellHeight)];
                [weakSelf.tableview reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
                
                }];
            }
    
}



- (ProductDetailWebFooterView *)webFooterView {
    if (!_webFooterView) {
        _webFooterView = [[ProductDetailWebFooterView alloc] initWithReuseIdentifier:nil];
        _webFooterView.backgroundColor = [UIColor redColor];
        _webFooterView.frame = CGRectMake(0, 0, self.view.bounds.size.width, 44);
        _webFooterView.navigationDelegate = self;
    }
    return _webFooterView;
}

- (UIView *)maskView {
    
    if (!_maskView) {
        _maskView = [[UIView alloc] init];
        _maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:@"X" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.layer.cornerRadius = 20.0f;
        btn.layer.borderWidth = 2.0f;
        btn.layer.borderColor  = [UIColor whiteColor].CGColor;
        [btn setBackgroundColor:[UIColor lightGrayColor]];
        [btn addTarget:self action:@selector(hideGoodsDetail) forControlEvents:UIControlEventTouchUpInside];
        [_maskView addSubview:btn];
        
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.mas_equalTo(30);
            make.width.height.mas_equalTo(40);
        }];
    }
    return _maskView;
}

- (UIImageView *)sunCodeImageView {
    if (!_sunCodeImageView) {
        _sunCodeImageView = [[UIImageView alloc] init];
        _sunCodeImageView.layer.cornerRadius = 5;
    }
    return _sunCodeImageView;
}

- (WKWebView *)VRView {
    if (!_VRView) {
        _VRView = [[WKWebView alloc] init];
        _VRView.scrollView.scrollEnabled = NO;
        _VRView.navigationDelegate = self;
        _VRView.tag = 100;
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:@"X" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.layer.cornerRadius = 20.0f;
        btn.layer.borderWidth = 2.0f;
        btn.layer.borderColor  = [UIColor whiteColor].CGColor;
        [btn setBackgroundColor:[UIColor lightGrayColor]];
        [btn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [_VRView addSubview:btn];
        
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.mas_equalTo(30);
            make.width.height.mas_equalTo(40);
        }];
        
        if (@available(iOS 11.0, *)) {
            _VRView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _VRView;
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];

        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerClass:[ProductDetailBannerCell class] forCellReuseIdentifier:@"bannerCellID"];
        [_tableview registerNib:[UINib nibWithNibName:@"ProductInfoCell" bundle:nil] forCellReuseIdentifier:@"ProductInfoCellID"];
        [_tableview registerNib:[UINib nibWithNibName:@"normalTableViewCell" bundle:nil] forCellReuseIdentifier:@"normalTableViewCellID"];
        [_tableview registerClass:[ProductSKUCell class] forCellReuseIdentifier:@"ProductSKUCellID"];
        
    }
    return _tableview;
}

#pragma mark 显示与隐藏商品详情页面
- (void)showGoodsDetail {
    
    self.maskView.hidden = NO;
    
    [self.tableview reloadData];
    
//    [webView evaluateJavaScript:@"document.body.offsetHeight;" completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
//        self.contextCellHeight = [obj floatValue];
//        [webView sizeThatFits:CGSizeMake(self.view.bounds.size.width, self.contextCellHeight)];
//        [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
//    }];
}

- (void)hideGoodsDetail {
    
    self.maskView.hidden = YES;
}

- (void)goAR {
    
    
    if (self.ARModelArray.count !=0) {
        
#if TARGET_IPHONE_SIMULATOR//模拟器
#elif TARGET_OS_IPHONE//真机
        Ar100Maganer *manager = [Ar100Maganer new];
        self.ar100Maganer = manager;
        [self.ar100Maganer init:self.ARModelArray decryptType:0 decryptKey:@""];
        self.ar100Maganer.allModels = self.ARModelArray;
        
        NSMutableArray<NSString *> *relatedIds = [NSMutableArray<NSString *> new];
        [relatedIds addObject:@"2"];
        [self.ar100Maganer showById:self modelId:@"1" relatedIds:relatedIds];
        
#endif
        
    } else {
        
        [WHToast showErrorWithMessage:@"当前商品无模型" duration:TT_GLOBAL_DURATION_TIME finishHandler:^{
            
        }];
    }
    

    
}

- (void)playVideo {
    
        NSString *webVideoPath = @"https://media.w3.org/2010/05/sintel/trailer.mp4";
        NSURL *webVideoUrl = [NSURL URLWithString:webVideoPath];
        //步骤2：创建AVPlayer
        AVPlayer *avPlayer = [[AVPlayer alloc] initWithURL:webVideoUrl];
        //步骤3：使用AVPlayer创建AVPlayerViewController，并跳转播放界面
        AVPlayerViewController *avPlayerVC =[[AVPlayerViewController alloc] init];
        avPlayerVC.player = avPlayer;
        [self presentViewController:avPlayerVC animated:YES completion:nil];
        [avPlayerVC.player play];
}

-(NSMutableArray *)bannerArray {
    
    if (!_bannerArray) {
        _bannerArray = [NSMutableArray new];
    }
    return _bannerArray;
}

- (UIButton *)panoramaBtn {
    if (!_panoramaBtn) {
        _panoramaBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_panoramaBtn setTitle:@"全景" forState:UIControlStateNormal];

        _panoramaBtn.layer.borderWidth = 1;
        [_panoramaBtn setBackgroundColor:UIColorHex(0x3c7ef4)];
        _panoramaBtn.layer.borderColor = UIColorHex(0x95c7f7).CGColor;
        _panoramaBtn.layer.cornerRadius = 25.0f;
    }
    return _panoramaBtn;
}

-(UIButton *)videoBtn {
    if (!_videoBtn) {
        _videoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_videoBtn setTitle:@"视频" forState:UIControlStateNormal];

        _videoBtn.layer.borderWidth = 1;
        [_videoBtn setBackgroundColor:UIColorHex(0x3c7ef4)];
        _videoBtn.layer.borderColor = UIColorHex(0x95c7f7).CGColor;
        _videoBtn.layer.cornerRadius = 25.0f;
        [_videoBtn addTarget:self action:@selector(playVideo) forControlEvents:UIControlEventTouchUpInside];

    }
    return _videoBtn;
}

- (UIButton *)arShopingBtn {
    if (!_arShopingBtn) {
        _arShopingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_arShopingBtn setTitle:@"AR购物" forState:UIControlStateNormal];
        _arShopingBtn.layer.borderWidth = 1;
        [_arShopingBtn setBackgroundColor:UIColorHex(0x3c7ef4)];
        _arShopingBtn.layer.borderColor = UIColorHex(0x95c7f7).CGColor;
        [_arShopingBtn addTarget:self action:@selector(goAR) forControlEvents:UIControlEventTouchUpInside];
        _arShopingBtn.layer.cornerRadius = 25.0f;
    }
    return _arShopingBtn;
}

- (UIButton *)detailBtn {
    if (!_detailBtn) {
        _detailBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_detailBtn setTitle:@"详情" forState:UIControlStateNormal];
        _detailBtn.layer.cornerRadius = 25.0f;
        _detailBtn.layer.borderWidth = 1;
        [_detailBtn setBackgroundColor:UIColorHex(0x3c7ef4)];
        _detailBtn.layer.borderColor = UIColorHex(0x95c7f7).CGColor;
        [_detailBtn addTarget:self action:@selector(showGoodsDetail) forControlEvents:UIControlEventTouchUpInside];
    }
    return _detailBtn;
}

@end
